package com.victor.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.victor.common.core.constant.CommonConstant;
import com.victor.common.core.context.SecurityContextHolder;
import com.victor.common.request.PageRequest;
import com.victor.common.request.system.SysHospitalPage;
import com.victor.common.response.system.OrgCodeAndOrgName;
import com.victor.system.service.SysHospitalService;
import com.victor.system.service.SysSubHospitalService;
import com.victor.common.core.utils.StringUtils;
import com.victor.common.core.utils.bean.BeanUtils;
import com.victor.common.dao.system.SysHospitalDao;
import com.victor.common.entity.system.SysHospital;
import com.victor.common.entity.system.SysSubHospital;
import com.victor.common.response.system.OrgInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Objects;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 医院信息表 服务实现类
 * </p>
 *
 * @author benetech
 * @since 2022年11月23日
 */
@Service
public class SysHospitalServiceImpl extends ServiceImpl<SysHospitalDao, SysHospital> implements SysHospitalService {

    @Autowired
    private SysSubHospitalService sysSubHospitalService;

    /**
     * 判断机构编码是否重复
     *
     * @param body
     * @return
     */
    @Override
    public Boolean checkHospital(SysHospital body) {
        Long integer = this.baseMapper.selectCount(new LambdaQueryWrapper<SysHospital>()
                .ne(body.getId() != null && body.getId() > 0, SysHospital::getId, body.getId())
                .and(wrapper -> wrapper.eq(StringUtils.isNotEmpty(body.getOrgCode()), SysHospital::getOrgCode, body.getOrgCode())
                        .or()
                        .eq(StringUtils.isNotEmpty(body.getOrgName()), SysHospital::getOrgName, body.getOrgName())));
        Long integerSub = sysSubHospitalService.getBaseMapper().selectCount(new LambdaQueryWrapper<SysSubHospital>()
                .or(wrapper -> wrapper.eq(StringUtils.isNotEmpty(body.getOrgCode()), SysSubHospital::getOrgSubCode, body.getOrgCode())
                        .eq(StringUtils.isNotEmpty(body.getOrgName()), SysSubHospital::getOrgSubName, body.getOrgName())));
        return integer > 0 || integerSub > 0;
    }

    /**
     * 机构列表查询
     *
     * @return
     */
    @Override
    public List<OrgInfo> getOrgList() {


        List<SysHospital> sysHospitals = this.baseMapper.selectList(new LambdaQueryWrapper<SysHospital>()
                .eq(SysHospital::getIsCommunity, CommonConstant.VALIDSTATUS_Y)
                .orderByAsc(SysHospital::getOrgCode));


        List<SysSubHospital> sysSubHospitals = sysSubHospitalService.getBaseMapper().selectList(new LambdaQueryWrapper<SysSubHospital>()
                .orderByAsc(SysSubHospital::getOrgSubCode));
        if (CollectionUtil.isEmpty(sysSubHospitals)) {
            sysSubHospitals = new ArrayList<>();
        }
        List<OrgInfo> orgInfos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sysHospitals)) {
            Map<String, List<SysSubHospital>> subHospitalMap = sysSubHospitals.stream().collect(Collectors.groupingBy(SysSubHospital::getOrgCode));
            for (SysHospital hospital : sysHospitals) {
                OrgInfo orgInfo = new OrgInfo();
                BeanUtils.copyProperties(hospital, orgInfo);
                orgInfo.setName(hospital.getOrgName());
                orgInfo.setSubList(subHospitalMap.get(hospital.getOrgCode()));
                orgInfos.add(orgInfo);
            }
        }
        return orgInfos;

    }

    /**
     * 更新机构以及子机构
     *
     * @param body
     * @return
     */
    @Override
    public boolean updateByIdAndSub(SysHospital body) {
        String orgCode = body.getOrgCode();
        if (StringUtils.isNotEmpty(orgCode)) {
            SysHospital hospital = this.baseMapper.selectById(body.getId());
            String oldOrgCode = hospital.getOrgCode();
            List<SysSubHospital> sysSubHospitals = sysSubHospitalService.getBaseMapper().selectList(new LambdaQueryWrapper<SysSubHospital>()
                    .eq(SysSubHospital::getOrgCode, oldOrgCode));
            sysSubHospitals.forEach(sub -> sub.setOrgCode(orgCode));
            sysSubHospitalService.updateBatchById(sysSubHospitals);
        }
        if(Objects.isNull(body.getOrgPic())){
            body.setOrgPic("");
        }
        if(Objects.isNull(body.getQrCodePic())){
            body.setQrCodePic("");
        }
        return this.updateById(body);
    }

    @Override
    public Page<OrgInfo> getOrgPage(SysHospitalPage info) {

        List<SysSubHospital> sysSubHospitals = sysSubHospitalService.getBaseMapper().selectList(new LambdaQueryWrapper<SysSubHospital>()
                .orderByAsc(SysSubHospital::getOrgSubCode));

        Page<OrgInfo> page = new Page<OrgInfo>(info.getCurrent(), info.getSize());
        Page<SysHospital> sysHospitalPage = new Page<SysHospital>(info.getCurrent(), info.getSize());
        sysHospitalPage = page(sysHospitalPage, new LambdaQueryWrapper<SysHospital>()
                        .like(SysHospital::getOrgName, info.getOrgName())
                        .orderByAsc(SysHospital::getOrgCode));
        BeanUtils.copyProperties(sysHospitalPage, page);
        List<SysHospital> hospitals = sysHospitalPage.getRecords();
        List<OrgInfo> orgInfos = new ArrayList<>();
        for (SysHospital hospital : hospitals) {
            OrgInfo orgInfo = new OrgInfo();
            BeanUtils.copyProperties(hospital, orgInfo);
            orgInfos.add(orgInfo);
        }
        page.setRecords(orgInfos);

        for (OrgInfo orgInfo : page.getRecords()) {

            Map<String, List<SysSubHospital>> subHospitalMap = sysSubHospitals.stream().collect(Collectors.groupingBy(SysSubHospital::getOrgCode));

            orgInfo.setName(orgInfo.getOrgName());
            orgInfo.setSubList(subHospitalMap.get(orgInfo.getOrgCode()));

        }

        return page;
    }

    @Override
    public Integer getRuleSystemType() {
        String hospitalId = SecurityContextHolder.getHospitalId();
        SysHospital hospital = getOne(new LambdaQueryWrapper<SysHospital>()
                .eq(SysHospital::getOrgCode, hospitalId));
        return ObjectUtil.isNotEmpty(hospital) ? hospital.getRuleSystemType() : 1;
    }

    @Override
    public List<OrgCodeAndOrgName> getOrgNameAndCommunity() {
        LambdaQueryWrapper<SysHospital> wrapper = new LambdaQueryWrapper<SysHospital>()
                .eq(SysHospital::getIsCommunity, CommonConstant.VALIDSTATUS_Y);
        List<SysHospital> info = list(wrapper);
        List<OrgCodeAndOrgName> orgCodeAndOrgNames = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(info)){
            info.forEach(e -> {
                OrgCodeAndOrgName orgCodeAndOrgName = new OrgCodeAndOrgName();
                orgCodeAndOrgName.setOrgCode(e.getOrgCode());
                orgCodeAndOrgName.setOrgName(e.getOrgName());
                orgCodeAndOrgName.setFtpPass(e.getFtpPass());
                orgCodeAndOrgName.setFtpUser(e.getFtpUser());
                orgCodeAndOrgNames.add(orgCodeAndOrgName);
            });
        }
        return orgCodeAndOrgNames;
    }



}
